package com.aipartner.service.impl;

import com.aipartner.common.PageResult;
import com.aipartner.dto.PaymentResponse;
import com.aipartner.dto.VipInfo;
import com.aipartner.dto.VipPlanResponse;
import com.aipartner.dto.VipPurchaseRequest;
import com.aipartner.dto.VipPackageRequest;
import com.aipartner.entity.User;
import com.aipartner.entity.VipOrder;
import com.aipartner.entity.VipPackage;
import com.aipartner.mapper.UserMapper;
import com.aipartner.mapper.VipOrderMapper;
import com.aipartner.mapper.VipPackageMapper;
import com.aipartner.service.VipService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * VIP Service Implementation
 * 
 * @author AI Partner Team
 * @since 2024-01-20
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class VipServiceImpl implements VipService {
    
    private final UserMapper userMapper;
    private final VipOrderMapper vipOrderMapper;
    private final VipPackageMapper vipPackageMapper;
    
    @Override
    public List<VipPlanResponse> getVipPlans() {
        try {
            QueryWrapper<VipPackage> wrapper = new QueryWrapper<>();
            wrapper.eq("status", 1) // 只查询启用的套餐
                   .orderByAsc("id");
            
            List<VipPackage> packages = vipPackageMapper.selectList(wrapper);
            
            log.info("用户端查询到{}个VIP套餐", packages.size());
            packages.forEach(pkg -> log.debug("套餐: id={}, name={}, status={}", 
                pkg.getId(), pkg.getName(), pkg.getStatus()));
            
            return packages.stream()
                    .map(this::convertToVipPlanResponse)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取VIP套餐列表失败", e);
            return new ArrayList<>();
        }
    }
    
    @Override
    public List<VipPlanResponse> getAdminVipPackages() {
        try {
            // 管理端查询所有套餐（物理删除后不需要过滤deleted字段）
            QueryWrapper<VipPackage> wrapper = new QueryWrapper<>();
            wrapper.orderByAsc("id");
            
            List<VipPackage> packages = vipPackageMapper.selectList(wrapper);
            
            log.info("管理端查询到{}个VIP套餐", packages.size());
            packages.forEach(pkg -> log.debug("管理端套餐: id={}, name={}, status={}", 
                pkg.getId(), pkg.getName(), pkg.getStatus()));
            
            return packages.stream()
                    .map(this::convertToVipPlanResponse)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取管理端VIP套餐列表失败", e);
            return new ArrayList<>();
        }
    }
    
    @Override
    public VipInfo getUserVipInfo(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            VipInfo emptyInfo = new VipInfo();
            emptyInfo.setIsVip(false);
            emptyInfo.setVipType(null);
            emptyInfo.setExpireTime(null);
            emptyInfo.setRemainingDays(0);
            return emptyInfo;
        }
        
        VipInfo vipInfo = new VipInfo();
        vipInfo.setIsVip(user.isVip());
        vipInfo.setVipType(user.getVipLevel() != null && user.getVipLevel() > 0 ? "custom" : null);
        vipInfo.setExpireTime(user.getVipExpireTime());
        
        if (user.getVipExpireTime() != null && user.isVip()) {
            long days = java.time.temporal.ChronoUnit.DAYS.between(LocalDateTime.now(), user.getVipExpireTime());
            vipInfo.setRemainingDays((int) Math.max(0, days));
        } else {
            vipInfo.setRemainingDays(0);
        }
        
        return vipInfo;
    }
    
    @Override
    @Transactional
    public PaymentResponse createVipOrder(VipPurchaseRequest request) {
        try {
            VipOrder order = new VipOrder();
            order.setOrderNo("VIP" + System.currentTimeMillis());
            order.setUserId(request.getUserId());
            order.setVipType(request.getVipType());
            order.setPaymentMethod(request.getPaymentMethod());
            order.setStatus("pending");
            
            List<VipPlanResponse> plans = getVipPlans();
            VipPlanResponse selectedPlan = plans.stream()
                .filter(p -> p.getType().equals(request.getVipType()))
                .findFirst()
                .orElse(null);
                
            if (selectedPlan == null) {
                PaymentResponse errorResponse = new PaymentResponse(null, null, null);
                errorResponse.setStatus("error");
                errorResponse.setMessage("Invalid VIP plan - Plan not found");
                return errorResponse;
            }
            
            order.setVipName(selectedPlan.getName());
            order.setAmount(selectedPlan.getOriginalPrice());
            order.setPaidAmount(selectedPlan.getPrice());
            
            vipOrderMapper.insert(order);
            
            String paymentUrl = simulatePayment(order);
            
            PaymentResponse response = new PaymentResponse(order.getOrderNo(), selectedPlan.getPrice(), request.getPaymentMethod());
            response.setStatus("success");
            response.setPaymentUrl(paymentUrl);
            response.setMessage("Payment initiated");
            return response;
            
        } catch (Exception e) {
            log.error("VIP purchase failed: {}", e.getMessage(), e);
            PaymentResponse errorResponse = new PaymentResponse(null, null, null);
            errorResponse.setStatus("error");
            errorResponse.setMessage("Purchase failed: " + e.getMessage());
            return errorResponse;
        }
    }
    
    @Override
    public PageResult<VipOrder> getUserOrders(Long userId, Long current, Long size) {
        Page<VipOrder> pageObj = new Page<>(current, size);
        QueryWrapper<VipOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.orderByDesc("create_time");
        
        IPage<VipOrder> result = vipOrderMapper.selectPage(pageObj, wrapper);
        
        return new PageResult<>(200, "Success", result.getRecords(), 
                               result.getTotal(), result.getPages(), 
                               result.getCurrent() > 1, result.getCurrent() < result.getPages(),
                               current.intValue(), size.intValue());
    }
    
    @Override
    @Transactional
    public boolean handlePaymentCallback(String orderNo, String transactionId, String status) {
        try {
            QueryWrapper<VipOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no", orderNo);
            VipOrder order = vipOrderMapper.selectOne(wrapper);
            
            if (order == null) {
                log.error("Order not found: {}", orderNo);
                return false;
            }
            
            if ("success".equals(status)) {
                order.setStatus("paid");
                order.setThirdPartyOrderNo(transactionId);
                order.setPaidTime(LocalDateTime.now());
                
                LocalDateTime expireTime = calculateVipExpireTime(order.getVipType());
                order.setExpireTime(expireTime);
                
                vipOrderMapper.updateById(order);
                
                User user = userMapper.selectById(order.getUserId());
                if (user != null) {
                    user.setVipLevel(1);
                    user.setVipExpireTime(expireTime);
                    userMapper.updateById(user);
                }
                
                return true;
            } else {
                order.setStatus("failed");
                vipOrderMapper.updateById(order);
                return false;
            }
            
        } catch (Exception e) {
            log.error("Payment callback processing failed: {}", e.getMessage(), e);
            return false;
        }
    }
    
    private String simulatePayment(VipOrder order) {
        return "https://payment.example.com/pay?order=" + order.getOrderNo() + "&amount=" + order.getPaidAmount();
    }
    
    private LocalDateTime calculateVipExpireTime(String vipType) {
        LocalDateTime now = LocalDateTime.now();
        switch (vipType) {
            case "daily":
                return now.plusDays(1);
            case "monthly":
                return now.plusMonths(1);
            case "quarterly":
                return now.plusMonths(3);
            case "yearly":
                return now.plusYears(1);
            case "lifetime":
                return now.plusYears(100);
            default:
                return now.plusDays(1);
        }
    }
    
    // ==================== 管理端方法实现 ====================
    
    @Override
    public Map<String, Object> getAdminVipStats() {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            // 查询VIP用户总数
            QueryWrapper<User> totalWrapper = new QueryWrapper<>();
            totalWrapper.gt("vip_level", 0);
            long totalVipUsers = userMapper.selectCount(totalWrapper);
            
            // 查询活跃VIP用户数（未过期）
            QueryWrapper<User> activeWrapper = new QueryWrapper<>();
            activeWrapper.gt("vip_level", 0)
                        .gt("vip_expire_time", LocalDateTime.now());
            long activeVipUsers = userMapper.selectCount(activeWrapper);
            
            // 查询本月VIP收入
            QueryWrapper<VipOrder> revenueWrapper = new QueryWrapper<>();
            LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
            revenueWrapper.eq("status", "paid")
                         .ge("paid_time", monthStart);
            List<VipOrder> monthOrders = vipOrderMapper.selectList(revenueWrapper);
            BigDecimal monthlyRevenue = monthOrders.stream()
                    .map(VipOrder::getPaidAmount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            // 计算转化率（简单模拟）
            QueryWrapper<User> allUsersWrapper = new QueryWrapper<>();
            long totalUsers = userMapper.selectCount(allUsersWrapper);
            double conversionRate = totalUsers > 0 ? (double) totalVipUsers / totalUsers * 100 : 0;
            
            stats.put("totalVipUsers", totalVipUsers);
            stats.put("activeVipUsers", activeVipUsers);
            stats.put("monthlyRevenue", monthlyRevenue);
            stats.put("conversionRate", Math.round(conversionRate * 100.0) / 100.0);
            
        } catch (Exception e) {
            log.error("获取VIP统计数据失败", e);
            // 返回默认值
            stats.put("totalVipUsers", 0);
            stats.put("activeVipUsers", 0);
            stats.put("monthlyRevenue", BigDecimal.ZERO);
            stats.put("conversionRate", 0.0);
        }
        
        return stats;
    }
    
    @Override
    public Page<User> getAdminVipUsers(Page<User> page, String keyword, String status, String level) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        
        // 只查询VIP用户
        wrapper.gt("vip_level", 0);
        
        // 关键词搜索
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like("nickname", keyword)
                           .or().like("phone", keyword)
                           .or().eq("id", keyword));
        }
        
        // VIP状态筛选
        if (StringUtils.hasText(status)) {
            LocalDateTime now = LocalDateTime.now();
            switch (status) {
                case "active":
                    wrapper.gt("vip_expire_time", now);
                    break;
                case "expired":
                    wrapper.le("vip_expire_time", now);
                    break;
                case "expiring":
                    LocalDateTime weekLater = now.plusDays(7);
                    wrapper.gt("vip_expire_time", now)
                           .le("vip_expire_time", weekLater);
                    break;
            }
        }
        
        // VIP等级筛选
        if (StringUtils.hasText(level)) {
            wrapper.eq("vip_level", level);
        }
        
        // 按到期时间排序
        wrapper.orderByDesc("vip_expire_time");
        
        return userMapper.selectPage(page, wrapper);
    }
    
    @Override
    @Transactional
    public boolean extendVipUser(Long userId, Integer duration, String durationType) {
        try {
            User user = userMapper.selectById(userId);
            if (user == null) {
                return false;
            }
            
            LocalDateTime currentExpireTime = user.getVipExpireTime();
            LocalDateTime now = LocalDateTime.now();
            
            // 如果当前VIP已过期，从现在开始计算
            LocalDateTime startTime = currentExpireTime != null && currentExpireTime.isAfter(now) 
                    ? currentExpireTime : now;
            
            LocalDateTime newExpireTime;
            switch (durationType) {
                case "day":
                    newExpireTime = startTime.plusDays(duration);
                    break;
                case "month":
                    newExpireTime = startTime.plusMonths(duration);
                    break;
                case "year":
                    newExpireTime = startTime.plusYears(duration);
                    break;
                default:
                    newExpireTime = startTime.plusDays(duration);
            }
            
            user.setVipExpireTime(newExpireTime);
            user.setVipLevel(Math.max(user.getVipLevel(), 1)); // 确保VIP等级至少为1
            
            return userMapper.updateById(user) > 0;
        } catch (Exception e) {
            log.error("VIP用户续期失败", e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean cancelUserVip(Long userId, String reason) {
        try {
            User user = userMapper.selectById(userId);
            if (user == null) {
                return false;
            }
            
            user.setVipLevel(0);
            user.setVipExpireTime(LocalDateTime.now());
            
            return userMapper.updateById(user) > 0;
        } catch (Exception e) {
            log.error("取消用户VIP失败", e);
            return false;
        }
    }
    
    @Override
    public boolean updateVipPackageStatus(Long packageId, Integer status) {
        try {
            VipPackage vipPackage = vipPackageMapper.selectById(packageId);
            if (vipPackage == null) {
                log.error("VIP套餐不存在：packageId={}", packageId);
                return false;
            }
            
            vipPackage.setStatus(status);
            int result = vipPackageMapper.updateById(vipPackage);
            
            log.info("更新VIP套餐状态：packageId={}, status={}, result={}", packageId, status, result);
            return result > 0;
        } catch (Exception e) {
            log.error("更新VIP套餐状态失败：packageId={}, status={}", packageId, status, e);
            return false;
        }
    }
    
    @Override
    public boolean deleteVipPackage(Long packageId) {
        try {
            VipPackage vipPackage = vipPackageMapper.selectById(packageId);
            if (vipPackage == null) {
                log.error("VIP套餐不存在：packageId={}", packageId);
                return false;
            }
            
            // 直接物理删除
            int result = vipPackageMapper.deleteById(packageId);
            
            log.info("物理删除VIP套餐：packageId={}, result={}", packageId, result);
            return result > 0;
        } catch (Exception e) {
            log.error("删除VIP套餐失败：packageId={}", packageId, e);
            return false;
        }
    }
    
    @Override
    public boolean createVipPackage(VipPackageRequest request) {
        try {
            // 检查套餐类型是否重复
            QueryWrapper<VipPackage> wrapper = new QueryWrapper<>();
            wrapper.eq("type", request.getType());
            
            VipPackage existingPackage = vipPackageMapper.selectOne(wrapper);
            if (existingPackage != null) {
                log.error("套餐类型已存在：type={}", request.getType());
                return false;
            }
            
            // 创建新套餐
            VipPackage vipPackage = new VipPackage();
            vipPackage.setType(request.getType());
            vipPackage.setName(request.getName());
            vipPackage.setPrice(request.getPrice());
            vipPackage.setOriginalPrice(request.getOriginalPrice());
            vipPackage.setDescription(request.getDescription());
            vipPackage.setDuration(request.getDuration());
            vipPackage.setRecommended(request.getRecommended());
            vipPackage.setStatus(request.getStatus());
            
            int result = vipPackageMapper.insert(vipPackage);
            log.info("创建VIP套餐：type={}, name={}, result={}", request.getType(), request.getName(), result);
            return result > 0;
        } catch (Exception e) {
            log.error("创建VIP套餐失败：type={}", request.getType(), e);
            return false;
        }
    }
    
    @Override
    public boolean updateVipPackage(Long packageId, VipPackageRequest request) {
        try {
            VipPackage vipPackage = vipPackageMapper.selectById(packageId);
            if (vipPackage == null) {
                log.error("VIP套餐不存在：packageId={}", packageId);
                return false;
            }
            
            // 检查套餐类型是否重复（排除当前套餐）
            QueryWrapper<VipPackage> wrapper = new QueryWrapper<>();
            wrapper.eq("type", request.getType())
                   .ne("id", packageId);
                   
            VipPackage existingPackage = vipPackageMapper.selectOne(wrapper);
            if (existingPackage != null) {
                log.error("套餐类型已存在：type={}, packageId={}", request.getType(), packageId);
                return false;
            }
            
            // 更新套餐信息
            vipPackage.setType(request.getType());
            vipPackage.setName(request.getName());
            vipPackage.setPrice(request.getPrice());
            vipPackage.setOriginalPrice(request.getOriginalPrice());
            vipPackage.setDescription(request.getDescription());
            vipPackage.setDuration(request.getDuration());
            vipPackage.setRecommended(request.getRecommended());
            vipPackage.setStatus(request.getStatus());
            
            int result = vipPackageMapper.updateById(vipPackage);
            log.info("更新VIP套餐：packageId={}, type={}, name={}, result={}", packageId, request.getType(), request.getName(), result);
            return result > 0;
        } catch (Exception e) {
            log.error("更新VIP套餐失败：packageId={}", packageId, e);
            return false;
        }
    }
    
    /**
     * 转换VipPackage到VipPlanResponse
     */
    private VipPlanResponse convertToVipPlanResponse(VipPackage vipPackage) {
        VipPlanResponse response = new VipPlanResponse();
        response.setId(vipPackage.getId());
        response.setType(vipPackage.getType());
        response.setName(vipPackage.getName());
        response.setPrice(vipPackage.getPrice());
        response.setOriginalPrice(vipPackage.getOriginalPrice());
        response.setDescription(vipPackage.getDescription());
        response.setDuration(vipPackage.getDuration());
        response.setRecommended(vipPackage.getRecommended());
        response.setStatus(vipPackage.getStatus());
        return response;
    }
    
    @Override
    public Page<VipOrder> getAdminVipOrders(Page<VipOrder> page, String keyword, String status) {
        QueryWrapper<VipOrder> wrapper = new QueryWrapper<>();
        
        // 关键词搜索
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like("order_no", keyword)
                           .or().eq("user_id", keyword));
        }
        
        // 订单状态筛选
        if (StringUtils.hasText(status)) {
            wrapper.eq("status", status);
        }
        
        // 按创建时间排序
        wrapper.orderByDesc("create_time");
        
        return vipOrderMapper.selectPage(page, wrapper);
    }
    
    @Override
    @Transactional
    public boolean refundVipOrder(String orderNo, String reason, BigDecimal amount) {
        try {
            QueryWrapper<VipOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no", orderNo);
            VipOrder order = vipOrderMapper.selectOne(wrapper);
            
            if (order == null) {
                return false;
            }
            
            // 检查订单状态
            if (!"paid".equals(order.getStatus())) {
                return false; // 只有已支付的订单才能退款
            }
            
            // 更新订单状态为已退款
            order.setStatus("refunded");
            // 将退款信息记录到备注中
            BigDecimal refundAmount = amount != null ? amount : order.getPaidAmount();
            String refundInfo = "退款原因: " + reason + "; 退款金额: " + refundAmount + "; 退款时间: " + LocalDateTime.now();
            order.setRemark(order.getRemark() == null ? refundInfo : order.getRemark() + "; " + refundInfo);
            
            boolean updateSuccess = vipOrderMapper.updateById(order) > 0;
            
            if (updateSuccess) {
                // 如果退款成功，取消用户的VIP
                User user = userMapper.selectById(order.getUserId());
                if (user != null && user.getVipLevel() > 0) {
                    user.setVipLevel(0);
                    user.setVipExpireTime(LocalDateTime.now());
                    userMapper.updateById(user);
                }
            }
            
            return updateSuccess;
        } catch (Exception e) {
            log.error("VIP订单退款失败", e);
            return false;
        }
    }
}